#!/bin/bash

# 简化的Go隧道管理器构建和签名脚本
# 一键构建动态库并自动签名

set -e

echo "🔨 开始构建和签名Go隧道管理器..."

# 检查Go环境
if ! command -v go &> /dev/null; then
    echo "❌ Go未安装或不在PATH中"
    exit 1
fi

echo "✅ Go版本: $(go version)"

# 创建输出目录（统一使用assets/libs）
OUTPUT_DIR="../assets/libs"
mkdir -p "$OUTPUT_DIR"

# 获取当前平台
PLATFORM=$(uname -s)
ARCH=$(uname -m)

echo "📋 构建平台: $PLATFORM $ARCH"

# 设置输出文件名
if [[ "$PLATFORM" == "Darwin" ]]; then
    if [[ "$ARCH" == "arm64" ]]; then
        OUTPUT_FILE="$OUTPUT_DIR/libsimple_tunnel_darwin_arm64.dylib"
        export GOARCH=arm64
    else
        OUTPUT_FILE="$OUTPUT_DIR/libsimple_tunnel_darwin_amd64.dylib"
        export GOARCH=amd64
    fi
    export CGO_ENABLED=1
    export GOOS=darwin
else
    echo "❌ 此脚本仅支持macOS平台"
    exit 1
fi

echo "📦 输出文件: $OUTPUT_FILE"

# 清理之前的构建
if [[ -f "$OUTPUT_FILE" ]]; then
    echo "🗑️ 清理之前的构建文件..."
    rm -f "$OUTPUT_FILE"
    rm -f "${OUTPUT_FILE%.dylib}.h"
fi

# 构建动态库
echo "🔨 开始编译..."
BUILD_FLAGS="-ldflags=-s -ldflags=-w"  # 减小文件大小
if [[ "$1" == "debug" ]]; then
    BUILD_FLAGS=""
    echo "🐛 调试模式构建"
else
    echo "🚀 发布模式构建"
fi

go build -buildmode=c-shared $BUILD_FLAGS -o "$OUTPUT_FILE" *.go

# 检查构建结果
if [[ ! -f "$OUTPUT_FILE" ]]; then
    echo "❌ 构建失败!"
    exit 1
fi

echo "✅ 构建成功!"
echo "📊 文件大小: $(ls -lh "$OUTPUT_FILE" | awk '{print $5}')"

# macOS代码签名
echo "🔐 开始代码签名..."

# 查找签名身份
CERT_NAME=$(security find-identity -v -p codesigning | grep "Developer ID Application" | head -n 1 | sed -E 's/.*"(.*)".*/\1/')

if [ -z "$CERT_NAME" ]; then
    # 查找Mac Developer证书
    CERT_NAME=$(security find-identity -v -p codesigning | grep "Mac Developer" | head -n 1 | sed -E 's/.*"(.*)".*/\1/')
fi

if [ -z "$CERT_NAME" ]; then
    # 查找Apple Development证书
    CERT_NAME=$(security find-identity -v -p codesigning | grep "Apple Development" | head -n 1 | sed -E 's/.*"(.*)".*/\1/')
fi

if [ -z "$CERT_NAME" ]; then
    echo "⚠️ 未找到开发者证书，使用临时签名"
    SIGN_IDENTITY="-"
else
    echo "✅ 找到开发者证书: $CERT_NAME"
    SIGN_IDENTITY="$CERT_NAME"
fi

# 执行签名（尝试多种策略）
echo "🔏 签名文件: $OUTPUT_FILE"

if codesign --force --sign "$SIGN_IDENTITY" --timestamp --options runtime "$OUTPUT_FILE" 2>/dev/null; then
    echo "✅ 完整签名成功"
elif codesign --force --sign "$SIGN_IDENTITY" --timestamp "$OUTPUT_FILE" 2>/dev/null; then
    echo "✅ 时间戳签名成功"
elif codesign --force --sign "$SIGN_IDENTITY" "$OUTPUT_FILE" 2>/dev/null; then
    echo "✅ 基本签名成功"
else
    echo "❌ 签名失败"
    exit 1
fi

# 验证签名
echo "🔍 验证签名..."
if codesign --verify --verbose "$OUTPUT_FILE" 2>/dev/null; then
    echo "✅ 签名验证成功"
else
    echo "⚠️ 签名验证失败，但继续"
fi

# 显示库信息
echo ""
echo "📋 库信息:"
file "$OUTPUT_FILE"
echo ""
echo "🔗 依赖库:"
otool -L "$OUTPUT_FILE" | head -5
echo ""
echo "🔐 签名详情:"
codesign --display --verbose "$OUTPUT_FILE" 2>&1 | head -3 || echo "无签名信息"

# 检查头文件
HEADER_FILE="${OUTPUT_FILE%.dylib}.h"
if [[ -f "$HEADER_FILE" ]]; then
    echo ""
    echo "✅ 头文件已生成: $HEADER_FILE"
    echo "📋 导出函数数量: $(grep -c "extern" "$HEADER_FILE" || echo "0")"
else
    echo ""
    echo "⚠️ 头文件未生成"
fi

echo ""
echo "🎉 构建和签名完成!"
echo ""
echo "📁 生成的文件:"
echo "   - $OUTPUT_FILE (动态库)"
if [[ -f "$HEADER_FILE" ]]; then
    echo "   - $HEADER_FILE (头文件)"
fi
echo ""
echo "🚀 现在可以在Flutter中使用了！"

# 可选：生成Flutter绑定
if command -v dart &> /dev/null && [[ -f "ffigen.yaml" ]]; then
    echo ""
    echo "📝 生成Flutter FFI绑定..."
    if dart run ffigen --config ffigen.yaml 2>/dev/null; then
        echo "✅ Flutter绑定生成成功"
    else
        echo "⚠️ Flutter绑定生成失败，请手动运行: dart run ffigen --config ffigen.yaml"
    fi
fi

echo ""
echo "✨ 全部完成！"

